import { useContext } from "react";
import GanttContext from "../../../gantt/context";
import { cn } from "../../../../lib/utils";
import { ChevronDown, ChevronRight } from "../../components/icons";
import type { RenderItemProps } from "../../components/virtual-list";

export function TaskItem({ task, index }: RenderItemProps) {
    const { hoverTaskId, setHoverTaskId, toggleExpand } = useContext(GanttContext);
    const handleToggleExpand = (e: React.MouseEvent) => {
        e.stopPropagation();
        if (task.children && task.children.length > 0) {
            toggleExpand(task.id);
        }
    };
    return <div
        className={cn({
            "flex justify-center items-center h-12 hover:cursor-pointer text-gray-600": true,
            "bg-gray-100": index % 2 !== 0,
            "bg-orange-100": task.id == hoverTaskId,
        })}
        onMouseOver={() => setHoverTaskId(task.id)}
        onMouseOut={() => setHoverTaskId("")}
        key={task.id}
    >
        <div
            className="flex-1 flex items-center"
            style={{ paddingLeft: `${8 + task.level * 20}px` }}
        >
            {task.children && task.children.length > 0 ? (
                <button
                    onClick={handleToggleExpand}
                    className="mr-2 p-1 rounded transition-colors bg-orange-300 hover:bg-orange-400 hover:cursor-pointer"
                >
                    {task.expanded ? (
                        <ChevronDown size={16} className="text-white" />
                    ) : (
                        <ChevronRight size={16} className="text-white" />
                    )}
                </button>
            ) : (
                <div className="w-6 mr-2" /> // 占位符，保持对齐
            )}
            <span className="truncate">{task.name}</span>
        </div>
        <div className="w-28 flex items-center text-sm">
            {task.start.format("YYYY-MM-DD")}
        </div>
        <div className="w-28 flex items-center text-sm">
            {task.end.format("YYYY-MM-DD")}
        </div>
        <div className="w-20 flex justify-center">
            <div className="w-12 text-center text-xs bg-white text-orange-500 px-2 py-1 border-1 rounded">
                {task.progress}%
            </div>
        </div>
    </div>
}

export default TaskItem;
